<template>
  <a-tree
    :load-data="onLoadData"
    :tree-data="treeData"
    v-model:expandedKeys="expandedKeys"
    v-model:selectedKeys="selectedKeys"
    @select="onSelect"
  />
</template>
<script>
  import { defineComponent, ref } from 'vue'
  import { GetDictByPid } from '@/api/dictionary/api'
  export default defineComponent({
    props: {
      data: {
        type: Array,
        default: null,
      },
    },
    emits: ['selectedKey'],
    setup(props, context) {
      const expandedKeys = ref([])
      const selectedKeys = ref([])
      const treeData = ref(JSON.parse(JSON.stringify(props.data)))
      const onLoadData = (treeNode) => {
        return new Promise((resolve) => {
          if (treeNode.dataRef.children) {
            console.log('抛出')
            resolve()
            return
          }

          GetDictByPid({ id: treeNode.eventKey, bChild: true }).then((res) => {
            if (res.isSuccess && res.content.length > 0) {
              console.log(res)
              setTimeout(() => {
                var childs = []
                res.content.forEach((element) => {
                  childs.push({
                    title: element.name,
                    key: element.id,
                    isLeaf: element.count === 0,
                  })
                })
                treeNode.dataRef.children = childs
                console.log()
                treeData.value = [...treeData.value]
                resolve()
              }, 500)
            }
          })
        })
      }
      const onSelect = (selectedKeys, info) => {
        context.emit('selectedKey', info.node.eventKey)
      }

      return {
        expandedKeys,
        selectedKeys,
        treeData,
        onLoadData,
        onSelect,
      }
    },
    created() {},
  })
</script>
